package com.knowledge.plus.java8;

import com.knowledge.plus.java8.pojo.Java8Message;
import org.junit.Test;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 集合运算
 *
 * @author TPF
 * @since 2022/11/18
 */
public class CollectStatistic {

    Stream<String> stringStream = Stream.of("John", "Alice", "Bob");
    Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 5);
    Stream<Double> doubleStream = Stream.of(1.0, 2.0, 3.0, 4.0, 5.0);
    List<Java8Message> list = Java8Message.getMessageList();

    @Test
    public void statisticsList() {
        /*
         * 求和
         */
        int int1 = integerStream.mapToInt(Integer::intValue).sum();
        long long1 = list.stream().collect(Collectors.summingLong(Java8Message::getId));
        long long2 = list.stream().mapToLong(Java8Message::getId).sum();

        /*
         * 根据指定的比较器选择流中的最小元素
         */
        Optional<String> minName1 = stringStream.collect(Collectors.minBy(Comparator.naturalOrder()));
        Optional<String> minName2 = stringStream.min(Comparator.naturalOrder());

        /*
         * 根据指定的比较器选择流中的最大元素
         */
        Optional<String> maxName1 = stringStream.collect(Collectors.maxBy(Comparator.naturalOrder()));
        Optional<String> maxName2 = stringStream.max(Comparator.naturalOrder());

        /*
         * 对流中的元素进行求平均值，返回一个 double 类型
         */
        double average = integerStream.collect(Collectors.averagingInt(Integer::intValue));

        /*
         * 对流中的元素进行求和，返回一个 double 类型
         */
        int sum = integerStream.mapToInt(Integer::intValue).sum();
        double summingDouble1 = doubleStream.collect(Collectors.summingDouble(Double::doubleValue));
        double summingDouble2 = doubleStream.mapToDouble(Double::doubleValue).sum();

        /*
         * 对流中的元素进行计数
         */
        long count1 = stringStream.collect(Collectors.counting());
        long count2 = stringStream.count();

        /*
         * 对流中的元素进行统计，返回一个统计结果对象
         */
        IntSummaryStatistics iss = integerStream.collect(Collectors.summarizingInt(Integer::intValue));
        LongSummaryStatistics lss = list.stream().collect(Collectors.summarizingLong(Java8Message::getId));
        System.out.println("sum = " + lss.getSum());
        System.out.println("max = " + lss.getMax());
        System.out.println("min = " + lss.getMin());
        System.out.println("avg = " + lss.getAverage());
    }

}
